<template>
	<el-dialog title="填写出库单" v-model="visible" :close-on-click-modal="false" draggable width="780px">
		<el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="120px" v-loading="loading">
			<el-row :gutter="24">
				<el-col :span="12" class="mb-4">
					<el-form-item label="出库模式" prop="outInventoryType">
						<el-select v-model="form.outInventoryType">
							<el-option label="默认出库" :value="10" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb-4">
					<el-form-item label="选择单位" prop="customerDeptId">
						<el-tree-select
							v-model="form.customerDeptId"
							:data="parentData"
							:props="{ value: 'id', label: 'name', children: 'children', disabled: 'isLock' }"
							clearable
							filterable
							check-strictly
							default-expand-all
							:render-after-expand="false"
							placeholder="请选择单位"
							ref="treeRef"
							@change="handleDeptChange"
							@current-change="handleCurrentChange"
						/>
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb-4">
					<el-form-item label="平台使用年限" prop="platformFeeYears">
						<el-select v-model="form.platformFeeYears">
							<el-option v-for="item in platformFeeYearsOptions" :key="item.id" :label="item.label" :value="item.value" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb-4">
					<el-form-item label="通讯费配置" prop="isCommunicationFees">
						<el-select v-model="form.isCommunicationFees">
							<el-option label="不需要" :value="10" />
							<el-option label="需要" :value="20" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="isAllocationType20 ? 12 : 24" class="mb-4" v-if="form.isCommunicationFees === 20">
					<el-form-item label="配置方式" prop="deliveryMethod">
						<el-radio-group class="ml-4" v-model="form.deliveryMethod">
							<el-radio :label="10">配送</el-radio>
							<!-- <el-radio :label="20">代付</el-radio> -->
						</el-radio-group>
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb-4" v-if="isAllocationType20">
					<el-form-item label="有效期" prop="expirationDate">
						<el-date-picker
							type="datetime"
							v-model="form.expirationDate"
							placeholder="选择截止日期"
							:disabled-date="handleDisabledDate"
							value-format="YYYY-MM-DD HH:mm:ss"
						/>
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb-4" v-if="form.deliveryMethod === 10 && form.isCommunicationFees === 20">
					<el-form-item label="语音数/台" prop="ttsNum">
						<el-input-number :controls="false" v-model="form.ttsNum" :min="0" :value-on-clear="0" :max="99999" :precision="0" />
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb-4" v-if="form.deliveryMethod === 10 && form.isCommunicationFees === 20">
					<el-form-item label="短信数/台" prop="smsNum">
						<el-input-number v-model="form.smsNum" :controls="false" :min="0" :value-on-clear="0" :max="99999" :precision="0" />
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb-4" v-if="isAllocationType20">
					<el-form-item label="语音总数/台" prop="ttsTotalLimit">
						<template #label>
							<label> <span class="text-error">*</span>语音总数/台</label>
						</template>
						<div class="flex items-center">
							<el-input-number
								:controls="false"
								v-model="form.ttsTotalLimit"
								:min="0"
								:max="99999"
								:precision="0"
								:value-on-clear="0"
								:disabled="form.checkStatus_ttsTotalLimit === 20"
							/>
							<el-checkbox class="ml-1" v-model="form.checkStatus_ttsTotalLimit" :true-label="20" :false-label="10" border>不限制</el-checkbox>
						</div>
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb-4" v-if="isAllocationType20">
					<el-form-item label="短信总数/台" prop="smsTotalLimit">
						<template #label>
							<label> <span class="text-error">*</span>短信总数/台</label>
						</template>
						<div class="flex items-center">
							<el-input-number
								:controls="false"
								v-model="form.smsTotalLimit"
								:min="0"
								:max="99999"
								:precision="0"
								:value-on-clear="0"
								:disabled="form.checkStatus_smsTotalLimit === 20"
							/>
							<el-checkbox class="ml-1" v-model="form.checkStatus_smsTotalLimit" :true-label="20" :false-label="10" border>不限制</el-checkbox>
						</div>
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb-4" v-if="isAllocationType20">
					<el-form-item label="语音日限/台" prop="ttsSumDay">
						<template #label>
							<label> <span class="text-error">*</span>语音日限/台</label>
						</template>
						<div class="flex items-center">
							<el-input-number
								:controls="false"
								v-model="form.ttsSumDay"
								:min="0"
								:max="99999"
								:precision="0"
								:value-on-clear="0"
								:disabled="form.checkStatus_ttsSumDay === 20"
							/>
							<el-checkbox class="ml-1" v-model="form.checkStatus_ttsSumDay" :true-label="20" :false-label="10" border>不限制</el-checkbox>
						</div>
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb-4" v-if="isAllocationType20">
					<el-form-item label="短信日限/台" prop="smsSumDay">
						<template #label>
							<label> <span class="text-error">*</span>短信日限/台</label>
						</template>
						<div class="flex items-center">
							<el-input-number
								:controls="false"
								v-model="form.smsSumDay"
								:min="0"
								:max="99999"
								:precision="0"
								:value-on-clear="0"
								:disabled="form.checkStatus_smsSumDay === 20"
							/>
							<el-checkbox class="ml-1" v-model="form.checkStatus_smsSumDay" :true-label="20" :false-label="10" border>不限制</el-checkbox>
						</div>
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb-4" v-if="isAllocationType20">
					<el-form-item label="语音月限/台" prop="ttsSumMonth">
						<template #label>
							<label> <span class="text-error">*</span>语音月限/台</label>
						</template>
						<div class="flex items-center">
							<el-input-number
								:controls="false"
								v-model="form.ttsSumMonth"
								:min="0"
								:max="99999"
								:precision="0"
								:value-on-clear="0"
								:disabled="form.checkStatus_ttsSumMonth === 20"
							/>
							<el-checkbox class="ml-1" v-model="form.checkStatus_ttsSumMonth" :true-label="20" :false-label="10" border>不限制</el-checkbox>
						</div>
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb-4" v-if="isAllocationType20">
					<el-form-item label="短信月限/台" prop="smsSumMonth">
						<template #label>
							<label> <span class="text-error">*</span>短信月限/台</label>
						</template>
						<div class="flex items-center">
							<el-input-number
								:controls="false"
								v-model="form.smsSumMonth"
								:min="0"
								:max="99999"
								:precision="0"
								:value-on-clear="0"
								:disabled="form.checkStatus_smsSumMonth === 20"
							/>
							<el-checkbox class="ml-1" v-model="form.checkStatus_smsSumMonth" :true-label="20" :false-label="10" border>不限制</el-checkbox>
						</div>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<el-divider content-position="left">出库设备</el-divider>
		<div>
			<el-table
				:data="tableData"
				max-height="240"
				size="small"
				border
				:cell-style="tableStyle.cellStyle"
				:header-cell-style="tableStyle.headerCellStyle"
			>
				<el-table-column type="index" label="序号" width="60" />
				<el-table-column prop="imei" label="IMEI" show-overflow-tooltip />
				<el-table-column prop="deviceType" label="类型-型号" show-overflow-tooltip>
					<template #default="{ row }">
						<div class="flex justify-center">
							<span>{{ row.deviceType }}</span>
							<span class="px-1">-</span>
							<span>{{ row.deviceModelName }}</span>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="createTime" label="生产时间" show-overflow-tooltip />
				<el-table-column label="操作" width="80">
					<template #default="{ index }">
						<el-button size="small" type="danger" @click="handleDelete(index)">移除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<el-divider content-position="left" v-if="form.isCommunicationFees === 20">出库汇总</el-divider>
		<div v-if="form.isCommunicationFees === 20">
			<el-table
				:data="tableDataSort"
				max-height="240"
				size="small"
				border
				:cell-style="tableStyle.cellStyle"
				:header-cell-style="tableStyle.headerCellStyle"
			>
				<el-table-column type="index" label="序号" width="60" />
				<el-table-column prop="imei" label="单位" show-overflow-tooltip>
					<template #default>{{ form?.deptName }} </template>
				</el-table-column>
				<el-table-column prop="deviceType" label="类型-型号" show-overflow-tooltip>
					<template #default="{ row }">
						<div class="flex justify-center">
							<span>{{ row.deviceType }}</span>
							<span class="px-1">-</span>
							<span>{{ row.deviceModelName }}</span>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="createTime" label="平台使用年限(年)" show-overflow-tooltip>
					<template #default>{{ form.platformFeeYears }} </template>
				</el-table-column>
				<el-table-column prop="deviceNum" label="设备数" show-overflow-tooltip width="80" />
				<el-table-column prop="deviceType" label="语音数(分钟)" show-overflow-tooltip width="90">
					<template #default="{ row }">
						{{
							form.deliveryMethod === 20
								? form.checkStatus_ttsTotalLimit === 20
									? '无限制'
									: form.ttsTotalLimit * row.deviceNum
								: form.ttsNum * row.deviceNum
						}}
					</template>
				</el-table-column>
				<el-table-column prop="deviceModelName" label="短信数(条)" show-overflow-tooltip width="90">
					<template #default="{ row }">
						{{
							form.deliveryMethod === 20
								? form.checkStatus_smsTotalLimit === 20
									? '无限制'
									: form.smsTotalLimit * row.deviceNum
								: form.smsNum * row.deviceNum
						}}
					</template>
				</el-table-column>
			</el-table>
		</div>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="visible = false">取消</el-button>
				<el-button type="primary" @click="onSubmit" :disabled="!tableData.length || loading">确认</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { cloneDeep } from 'lodash';
import { computed } from 'vue';
import { useMessageBox } from '/@/hooks/message';
import { useTable } from '/@/hooks/table';
import { deptTree } from '/@/api/admin/dept';
import { addObj, getPlatformFeeYears } from '/@/api/platform/basicInventoryList';
import { useMessage } from '/@/hooks/message';
import { validateNull } from '/@/utils/validate';
const emit = defineEmits(['refresh']);
interface ListItem {
	label: string;
	value: number;
	id: number;
}
const { tableStyle } = useTable({});
const visible = ref(false);
const dataFormRef = ref();
const loading = ref(false);
const parentData = ref([]);
const platformFeeYearsOptions = ref<ListItem[]>([]);
// 提交表单数据
const form = reactive({
	id: '',
	outInventoryType: 10,
	platformFeeYears: null,
	expirationDate: null,
	isCommunicationFees: 10,
	deliveryMethod: 10,
	deviceSum: '',
	deviceId: '',
	outboundOrder: '',
	customerDeptId: null,
	ttsTotalLimit: 0,
	checkStatus_ttsTotalLimit: 10,
	checkStatus_ttsSumDay: 10,
	checkStatus_ttsSumMonth: 10,
	checkStatus_smsTotalLimit: 10,
	checkStatus_smsSumDay: 10,
	checkStatus_smsSumMonth: 10,
	deptName: '',
	smsSumMonth: 0,
	smsSumDay: 0,
	smsTotalLimit: 0,
	ttsSumDay: 0,
	ttsSumMonth: 0,
	ttsNum: 0,
	smsNum: 0,
});
// 定义校验规则
const dataRules = ref({
	customerDeptId: [{ required: true, message: '请选择单位', trigger: 'change' }],
	expirationDate: [{ required: true, message: '请选择有效期', trigger: 'change' }],
	platformFeeYears: [{ required: true, message: '请选择平台使用年限', trigger: 'change' }],
	ttsNum: [
		{ required: true, message: '请输入', trigger: 'blur' },
		{
			validator: (r: any, value: any, callback: any) => {
				if (validateNull(value) || value > 99999) callback(new Error('请输入0-99999的正整数'));

				callback();
			},
		},
	],
	smsNum: [
		{ required: true, message: '请输入', trigger: 'blur' },
		{
			validator: (r: any, value: any, callback: any) => {
				if (validateNull(value) || value > 99999) callback(new Error('请输入0-99999的正整数'));
				callback();
			},
		},
	],
	ttsTotalLimit: [
		{
			validator: (r: any, value: any, callback: any) => {
				if (form.checkStatus_ttsTotalLimit === 10) {
					if (validateNull(value) || value > 99999) callback(new Error('请输入0-99999的正整数'));
				}
				callback();
			},
		},
	],
	smsTotalLimit: [
		{
			validator: (r: any, value: any, callback: any) => {
				if (form.checkStatus_smsTotalLimit === 10) {
					if (validateNull(value) || value > 99999) callback(new Error('请输入0-99999的正整数'));
				}
				callback();
			},
		},
	],
	ttsSumDay: [
		{
			validator: (r: any, value: any, callback: any) => {
				if (form.checkStatus_ttsSumDay === 10) {
					if (validateNull(value) || value > 99999) callback(new Error('请输入0-99999的正整数'));
				}
				callback();
			},
		},
	],
	ttsSumMonth: [
		{
			validator: (r: any, value: any, callback: any) => {
				if (form.checkStatus_ttsSumMonth === 10) {
					if (validateNull(value) || value > 99999) callback(new Error('请输入0-99999的正整数'));
				}
				callback();
			},
		},
	],
	smsSumDay: [
		{
			validator: (r: any, value: any, callback: any) => {
				if (form.checkStatus_smsSumDay === 10) {
					if (validateNull(value) || value > 99999) callback(new Error('请输入0-99999的正整数'));
				}
				callback();
			},
		},
	],
	smsSumMonth: [
		{
			validator: (r: any, value: any, callback: any) => {
				if (form.checkStatus_smsSumMonth === 10) {
					if (validateNull(value) || value > 99999) callback(new Error('请输入0-99999的正整数'));
				}
				callback();
			},
		},
	],
});
const tableData: any = ref([]); //出库设备
const tableDataSort: any = ref([]); //出库汇总
// 打开弹窗
const openDialog = (rows: any) => {
	visible.value = true;
	tableData.value = cloneDeep(rows);
	// 重置表单数据
	nextTick(() => {
		dataFormRef.value?.resetFields();
	});
	getDeptData();
};
watchEffect(
	() => {
		if (!unref(tableData).length) return;
		const sortData: any[] = [];
		for (let i = 0; i < unref(tableData).length; i++) {
			const item = unref(tableData)[i];
			const index = sortData?.findIndex((d) => d.deviceTypeId === item.deviceTypeId && d.deviceModelId === item.deviceModelId);
			if (index !== -1) {
				sortData[index].deviceNum++;
			} else {
				const obj = Object.assign({}, item, { deviceNum: 1 });
				sortData.push(obj);
			}
		}
		tableDataSort.value = sortData;
	},
	{
		flush: 'post',
	}
);
// 代付
const isAllocationType20 = computed(() => {
	return form.deliveryMethod === 20 && form.isCommunicationFees === 20;
});
// 日期禁用
const handleDisabledDate = (date: Date) => {
	if (new Date(date).getTime() > new Date().getTime()) return false;
	return true;
};
const handleDelete = async (index: number) => {
	try {
		await useMessageBox().confirm('确定从该出库单中移除该设备吗？');
	} catch {
		return;
	}
	tableData.value.splice(index - 1, 1);
};
// 提交
const onSubmit = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;

	try {
		loading.value = true;
		const infinite = 999999;
		const deviceIds = tableData.value.map((d) => d.id);
		const infiniteObj = {
			ttsTotalLimit: form.checkStatus_ttsTotalLimit === 20 ? infinite : form.ttsTotalLimit,
			smsTotalLimit: form.checkStatus_smsTotalLimit === 20 ? infinite : form.smsTotalLimit,
			ttsSumDay: form.checkStatus_ttsSumDay === 20 ? infinite : form.ttsSumDay,
			smsSumDay: form.checkStatus_smsSumDay === 20 ? infinite : form.smsSumDay,
			ttsSumMonth: form.checkStatus_ttsSumMonth === 20 ? infinite : form.ttsSumMonth,
			smsSumMonth: form.checkStatus_smsSumMonth === 20 ? infinite : form.smsSumMonth,
			deviceIds: deviceIds,
		};
		const params = Object.assign({}, form, infiniteObj);
		await addObj(params);
		useMessage().success(form.id ? '修改成功' : '添加成功');
		visible.value = false;
		emit('refresh');
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};
const getDeptData = async () => {
	deptTree().then((res) => {
		parentData.value = res.data;
	});
};
const handleCurrentChange = (nodeData: any) => {
	form.deptName = nodeData.name;
};
const handleDeptChange = (id: string) => {
	form.platformFeeYears = null;
	platformFeeYearsOptions.value = [];
	getPlatformFeeYears(id).then((res) => {
		for (let i = 1; i <= res.data.length; i++) {
			platformFeeYearsOptions.value.push({
				id: i,
				label: `${i}年`,
				value: i,
			});
		}
	});
};
defineExpose({ openDialog });
</script>

<style lang="scss" scoped></style>
